package com.treasure.hunt.mode

import android.app.Activity
import android.app.Application
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.blankj.utilcode.util.ToastUtils
import com.bytedance.sdk.openadsdk.*
import com.kwai.monitor.log.TurboAgent
import com.module.lemlin.LoadingDialog
import com.module.lemlin.base.BaseApplication
import com.module.lemlin.base.BaseViewModel
import com.module.lemlin.mode.ViewModelSubscribe
import com.module.lemlin.rxhttp.HttpServiceResponse
import com.qq.e.ads.nativ.ADSize
import com.qq.e.ads.nativ.NativeExpressAD
import com.qq.e.ads.nativ.NativeExpressADView
import com.qq.e.ads.rewardvideo.RewardVideoAD
import com.qq.e.ads.rewardvideo.RewardVideoADListener
import com.qq.e.ads.splash.SplashAD
import com.qq.e.ads.splash.SplashADListener
import com.qq.e.comm.managers.GDTADManager
import com.qq.e.comm.util.AdError
import com.treasure.hunt.api.videoEnd
import com.treasure.hunt.api.videoNoReward
import com.treasure.hunt.api.videoType
import com.treasure.hunt.app.AppConstance
import com.treasure.hunt.dialog.LoadingDialog2
import com.treasure.hunt.entity.VideoEndResponse
import com.treasure.hunt.entity.VideoTypeResponse
import io.reactivex.rxjava3.disposables.Disposable

open class AdViewMode(application: Application) : BaseViewModel(application) {

    val videoTypeLiveData = MutableLiveData<HttpServiceResponse<VideoTypeResponse>>()
    val videoNoRewardLiveData = MutableLiveData<HttpServiceResponse<VideoTypeResponse>>()

    //    val videoNoRewardSignLiveData = MutableLiveData<HttpServiceResponse<VideoTypeResponse>>()
    val videoEndLiveData = MutableLiveData<HttpServiceResponse<VideoEndResponse>>()
    val isGoToMainActivityLiveData = MutableLiveData<Boolean>()
    val viewAdLiveData = MutableLiveData<View>()
    val rewardVerifyAdLiveData = MutableLiveData<Boolean>()

    var isRewardVerifyAdSign: Boolean = false


    fun videoNoReward(advertisementType: Int = 1) {
        val listener = object : ViewModelSubscribe<VideoTypeResponse>(videoNoRewardLiveData) {
            override fun onSuccess(resp: VideoTypeResponse) {
                if (resp.data.cid == 1) {
                    AppConstance.APP_ID_CSJ = resp.data.appid
                } else if (resp.data.cid == 2) {
                    AppConstance.APP_ID_YLH = resp.data.appid
                }
                super.onSuccess(resp)
            }
        }
        val disposable: Disposable =
            videoNoReward(advertisementType, listener)
        dispose.add(disposable)
    }

//    fun videoNoRewardSign(advertisementType: Int = 1) {
//        val listener = object : ViewModelSubscribe<VideoTypeResponse>(videoNoRewardSignLiveData) {
//            override fun onSuccess(resp: VideoTypeResponse) {
//                if (resp.data.cid == 1) {
//                    AppConstance.APP_ID_CSJ = resp.data.appid
//                } else if (resp.data.cid == 2) {
//                    AppConstance.APP_ID_YLH = resp.data.appid
//                }
//                super.onSuccess(resp)
//            }
//        }
//        val disposable: Disposable =
//            videoNoReward(advertisementType, listener)
//        dispose.add(disposable)
//    }

    private val mLoadingDialog2: LoadingDialog2 by lazy {
        LoadingDialog2(BaseApplication.INSTANCE)
    }

    fun videoType(maps: Map<String, Any?>) {
        val listener = object : ViewModelSubscribe<VideoTypeResponse>(videoTypeLiveData) {
            override fun onStart() {
                super.onStart()
                //mLoadingDialog2.showLoading()
                LoadingDialog.show(
                    BaseApplication.INSTANCE,
                    resId = com.treasure.hunt.R.layout.dialog_load_style_1
                )
            }

            override fun onSuccess(resp: VideoTypeResponse) {
                if (resp.data.cid == 1) {
                    AppConstance.APP_ID_CSJ = resp.data.appid
                } else if (resp.data.cid == 2) {
                    AppConstance.APP_ID_YLH = resp.data.appid
                }
                super.onSuccess(resp)
            }

            override fun onFailure(throwable: Throwable) {
                super.onFailure(throwable)
                LoadingDialog.dismiss()
            }
        }
        val disposable: Disposable =
            videoType(maps, listener)
        dispose.add(disposable)
    }

    fun videoEnd(videoLogId: String) {
        val disposable: Disposable =
            videoEnd(videoLogId, ViewModelSubscribe(videoEndLiveData))
        dispose.add(disposable)
    }

    private fun getTTAdNative(mActivity: Activity): TTAdNative {
        val ttAdManager: TTAdManager = TTAdSdk.init(
            mActivity, TTAdConfig.Builder()
                .appId(AppConstance.APP_ID_CSJ)
                .useTextureView(true) //使用TextureView控件播放视频,默认为SurfaceView,当有SurfaceView冲突的场景，可以使用TextureView
                .allowShowNotify(true) //是否允许sdk展示通知栏提示
                .debug(true) //测试阶段打开，可以通过日志排查问题，上线时去除该调用
                .directDownloadNetworkType(
                    TTAdConstant.NETWORK_STATE_WIFI,
                    TTAdConstant.NETWORK_STATE_3G
                ) //允许直接下载的网络状态集合
                .supportMultiProcess(true) //是否支持多进程
                .needClearTaskReset() //.httpStack(new MyOkStack3())//自定义网络库，demo中给出了okhttp3版本的样例，其余请自行开发或者咨询工作人员。
                .build()
        )
//        val ttAdManager: TTAdManager = TTAdManagerHolder.get()
        return ttAdManager.createAdNative(mActivity)
    }

    /**
     * 加载穿山甲开屏广告
     * */
    fun loadSplashAdCSJ(mActivity: Activity, codeId: String = "887446785") {

        getTTAdNative(mActivity).loadSplashAd(AdSlot.Builder()
            .setCodeId(codeId)
            .setImageAcceptedSize(1080, 1920)
            .build(), object : TTAdNative.SplashAdListener {
            override fun onSplashAdLoad(p0: TTSplashAd?) {
                if (p0 == null)
                    return
                viewAdLiveData.postValue(p0.splashView)
                p0.setSplashInteractionListener(object : TTSplashAd.AdInteractionListener {
                    override fun onAdClicked(p0: View?, p1: Int) {
                        LogUtils.e("=========onAdClicked=======")
                    }

                    override fun onAdSkip() {
                        isGoToMainActivityLiveData.postValue(true)
                    }

                    override fun onAdShow(p0: View?, p1: Int) {
                        LogUtils.e("=========onAdShow=======")
                    }

                    override fun onAdTimeOver() {
                        isGoToMainActivityLiveData.postValue(true)
                    }
                })
            }

            override fun onTimeout() {
                isGoToMainActivityLiveData.postValue(true)
            }

            override fun onError(p0: Int, p1: String?) {
                isGoToMainActivityLiveData.postValue(true)
            }
        })
    }

    /**
     * 加载优量汇开屏广告
     * */
    private var mSplashAD: SplashAD? = null
    fun loadSplashAdYLH(
        mActivity: Activity, codeId: String = "8061281018521404", container: ViewGroup
    ) {
        GDTADManager.getInstance().initWith(BaseApplication.INSTANCE, AppConstance.APP_ID_YLH)
        mSplashAD = SplashAD(mActivity, codeId, object : SplashADListener {
            override fun onADExposure() {
                LogUtils.e("=======onADExposure======")
            }

            override fun onADDismissed() {
                LogUtils.e("=======onADDismissed======")
                isGoToMainActivityLiveData.postValue(true)
            }

            override fun onADPresent() {
                LogUtils.e("=======onADPresent======")
            }

            override fun onADLoaded(p0: Long) {
                mSplashAD?.showFullScreenAd(container)
            }

            override fun onNoAD(p0: AdError?) {
                LogUtils.e("=======onNoAD======${p0?.errorCode}")
                isGoToMainActivityLiveData.postValue(true)
            }

            override fun onADClicked() {
                LogUtils.e("=======onADClicked======")
            }

            override fun onADTick(p0: Long) {
                LogUtils.e("=======onADTick======")
            }
        })
        mSplashAD?.fetchFullScreenAdOnly()

    }

    /**
     * 加载激励视频广告
     * */
    fun loadRewardVideoAdCSJ(mActivity: Activity, codeId: String = "945920419") {
        //TTAdManagerHolder.get().requestPermissionIfNecessary(mActivity)
        getTTAdNative(mActivity).loadRewardVideoAd(AdSlot.Builder()
            .setCodeId(codeId)
            .build(), object : TTAdNative.RewardVideoAdListener {
            override fun onRewardVideoAdLoad(p0: TTRewardVideoAd?) {
                LoadingDialog.dismiss()
                p0?.setRewardAdInteractionListener(object :
                    TTRewardVideoAd.RewardAdInteractionListener {
                    //视频播放完成后，奖励验证回调，rewardVerify：是否有效，rewardAmount：奖励梳理，rewardName：奖励名称
                    override fun onRewardVerify(
                        rewardVerify: Boolean, rewardAmount: Int, rewardName: String,
                        errorCode: Int, errorMsg: String
                    ) {
                        if (rewardVerify && errorCode == 0) {
//                            videoTypeLiveData.value?.httpData?.data?.let {
//                                videoEnd(it.video_log_id)
//                            }
//                            rewardVerifyAdSignLiveData.postValue(true)
                            rewardVerifyAdLiveData.postValue(true)
                            SPStaticUtils.put(
                                AppConstance.KEY_REGISTER_COUNT,
                                SPStaticUtils.getInt(AppConstance.KEY_REGISTER_COUNT, (0)) + 1
                            )
                            val registerCount =
                                SPStaticUtils.getInt(AppConstance.KEY_REGISTER_COUNT)
                            if (registerCount == 3) {
                                TurboAgent.onRegister()
                            }
                        } else {
                            ToastUtils.showShort("奖励验证回调错误：${errorMsg}")
                        }
                    }

                    override fun onSkippedVideo() = Unit

                    override fun onAdShow() = Unit

                    override fun onAdVideoBarClick() = Unit

                    override fun onVideoComplete() = Unit

                    override fun onAdClose() = Unit

                    override fun onVideoError() {
                        ToastUtils.showShort("视频广告播放错误")
                    }
                })

                p0?.showRewardVideoAd(
                    mActivity, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, "scenes_test"
                )
            }

            override fun onRewardVideoCached() {

            }

            override fun onError(p0: Int, p1: String?) {
                LoadingDialog.dismiss()
                ToastUtils.showShort("${p0}$p1")
            }
        })
    }

    /**
     * 加载激励视频广告
     * */
    private var mRewardVideoAD: RewardVideoAD? = null
    fun loadRewardVideoAdYLH(mActivity: Activity, codeId: String = "2031485048724561") {
        GDTADManager.getInstance().initWith(BaseApplication.INSTANCE, AppConstance.APP_ID_YLH)
        mRewardVideoAD = RewardVideoAD(mActivity, codeId, object : RewardVideoADListener {
            override fun onADExpose() {
                LogUtils.e("======onADExpose======")
            }

            override fun onADClick() {
                LogUtils.e("======onADClick======")
            }

            override fun onVideoCached() {
                LogUtils.e("======onVideoCached======")
            }

            override fun onReward(p0: MutableMap<String, Any>?) {
                rewardVerifyAdLiveData.postValue(true)
                SPStaticUtils.put(
                    AppConstance.KEY_REGISTER_COUNT,
                    SPStaticUtils.getInt(AppConstance.KEY_REGISTER_COUNT, (0)) + 1
                )
                val registerCount =
                    SPStaticUtils.getInt(AppConstance.KEY_REGISTER_COUNT)
                if (registerCount == 3) {
                    TurboAgent.onRegister()
                }
            }

            override fun onADClose() {
                LogUtils.e("======onADClose======")
            }

            override fun onADLoad() {
                LogUtils.e("======onADLoad======")
                LoadingDialog.dismiss()
                mRewardVideoAD?.showAD()
            }

            override fun onVideoComplete() {
                LogUtils.e("======onVideoComplete======")
            }

            override fun onError(p0: AdError?) {
                LoadingDialog.dismiss()
                ToastUtils.showShort("视频广告播放错误${p0?.errorMsg}")
            }

            override fun onADShow() {
                LogUtils.e("======onADShow======")
            }
        })
        mRewardVideoAD?.loadAD()
    }


    /**
     * 加载信息流广告
     * */
    fun loadNativeExpressAdCSJ(mActivity: Activity, codeId: String = "945907313") {

        getTTAdNative(mActivity).loadNativeExpressAd(AdSlot.Builder()
            .setCodeId(codeId) //广告位id
            .setAdCount(1) //请求广告数量为1到3条
            .build(), object : TTAdNative.NativeExpressAdListener {
            override fun onNativeExpressAdLoad(p0: MutableList<TTNativeExpressAd>?) {
                if (p0 == null || p0.size == 0)
                    return
                //showNativeExpressAd(p0[0])
                val mTTAd: TTNativeExpressAd = p0[0]
                mTTAd.setExpressInteractionListener(object :
                    TTNativeExpressAd.ExpressAdInteractionListener {
                    override fun onAdClicked(p0: View?, p1: Int) {
                        LogUtils.e("=========onAdClicked=======")
                    }

                    override fun onAdShow(p0: View?, p1: Int) {
                        LogUtils.e("=========onAdShow=======")
                    }

                    override fun onRenderSuccess(p0: View?, p1: Float, p2: Float) {
                        viewAdLiveData.postValue(p0)
                    }

                    override fun onRenderFail(p0: View?, p1: String?, p2: Int) {
                        LogUtils.e("=========onRenderFail=======")
                    }
                })
                mTTAd.render()
            }

            override fun onError(p0: Int, p1: String?) {
                LogUtils.e("=========onError${p0}${p1}=======")
                //5010广告样式校验失败，请检查广告位与接口使用是否一致
                //   {"code":1,"msg":"成功","time":"1619577312","data":{"num":5,"sort":0,"id":6,"cid":2,"advertisement_id":1,"advertising_space":"8061281018521404","name":"穿山甲优先","appid":"1111753420","video_log_id":"4133","type_text":"","switch_text":""}}
                ToastUtils.showShort("${p0}${p1}")
            }
        })
    }


    /**
     * 加载信息流广告
     * */
    private var mNativeExpressAD: NativeExpressAD? = null
    private var mNativeExpressADView: NativeExpressADView? = null
    fun loadNativeExpressAdYLH(mActivity: Activity, codeId: String = "9071788048226640") {
        GDTADManager.getInstance().initWith(BaseApplication.INSTANCE, AppConstance.APP_ID_YLH)
        mNativeExpressAD = NativeExpressAD(
            mActivity,
            ADSize(ADSize.FULL_WIDTH, ADSize.AUTO_HEIGHT),
            codeId,
            object :
                NativeExpressAD.NativeExpressADListener {
                override fun onADCloseOverlay(p0: NativeExpressADView?) {
                    LogUtils.e("=========onADCloseOverlay==========")
                }

                override fun onADLoaded(p0: MutableList<NativeExpressADView>?) {
                    LogUtils.e("=========onADLoaded==========")

                    mNativeExpressADView?.destroy()
                    mNativeExpressADView = p0?.get(0)

                    mNativeExpressADView?.render()

                    viewAdLiveData.postValue(mNativeExpressADView)
                }

                override fun onADOpenOverlay(p0: NativeExpressADView?) {
                    LogUtils.e("=========onADOpenOverlay==========")
                }

                override fun onRenderFail(p0: NativeExpressADView?) {
                    LogUtils.e("=========onRenderFail==========")
                }

                override fun onADExposure(p0: NativeExpressADView?) {
                    LogUtils.e("=========onADExposure==========")
                }

                override fun onADClosed(p0: NativeExpressADView?) {
                    LogUtils.e("=========onADClosed==========")
                }

                override fun onADLeftApplication(p0: NativeExpressADView?) {
                    LogUtils.e("=========onADLeftApplication==========")
                }

                override fun onNoAD(p0: AdError?) {
                    LogUtils.e("=========onNoAD:${p0?.errorCode}${p0?.errorMsg}==========")
                    ToastUtils.showShort("${p0?.errorMsg}")
                }

                override fun onADClicked(p0: NativeExpressADView?) {
                    LogUtils.e("=========onADClicked==========")
                }

                override fun onRenderSuccess(p0: NativeExpressADView?) {
                    LogUtils.e("=========onRenderSuccess==========")
                }

            })
        mNativeExpressAD?.loadAD(1)
    }
}